package com.ylx.excel.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.ylx.excel.excel.handler.SyncListener;
import com.ylx.excel.excel.model.SyncExcelData;
import com.ylx.excel.service.SyncExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程异步Excel
 * @author yanglixin
 */
@Slf4j
@Service
public class SyncExcelServiceImpl implements SyncExcelService {

    ExecutorService executorService = Executors.newFixedThreadPool(5);
    @Autowired
    private SyncListener syncListener;

    @Override
    public String syncImport(MultipartFile file, HttpServletResponse response) {
        List<Callable<Object>> tasks = new ArrayList<>();

        log.info("开始导入数据");
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {
            int num = i;
            tasks.add(() -> {
                EasyExcelFactory.read(file.getInputStream(), SyncExcelData.class,syncListener)
                        .sheet(num).doRead();
                return null;
            });
        }
        try {
            executorService.invokeAll(tasks);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 记录结束时间
        long endTime = System.currentTimeMillis();
        // 计算总耗时
        long totalTime = endTime - startTime;
        executorService.shutdown(); // 关闭线程池
        while (!executorService.isTerminated()) {
            // 等待所有线程完成
        }
        log.info("总耗时: {}s",totalTime/1000);
        return "导入中。。。";
    }

}
